﻿

using System;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
[AttributeUsage(AttributeTargets.Class)]
public class ErrorHandlerBehavior : Attribute, IServiceBehavior, IErrorHandler
{
    protected Type ServiceType
    { get; set; }

    #region IServiceBehavior Members

    void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    { }

    void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        ServiceType = serviceDescription.ServiceType;
        foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
        {
            dispatcher.ErrorHandlers.Add(this);
        }
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    { }

    #endregion

    #region IErrorHandler Members

    public static void Log(string Message)
    {
        ConnectionStringSettings ConnectionStringSettings =
      ConfigurationManager.ConnectionStrings["mainConn"];

        if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "")
        {
            throw new Exception("Connection string cannot be blank.");
        }

        var connectionString = ConnectionStringSettings.ConnectionString;


        SqlConnection conn = new SqlConnection(connectionString);




        SqlCommand cmd = new SqlCommand("INSERT INTO EventLog " +
        " (EventDate, EventDescription) " +
        " Values (@EventDate, @EventDescription)", conn);


        cmd.Parameters.Add("@EventDate", SqlDbType.DateTime).Value = DateTime.Now;
        cmd.Parameters.Add("@EventDescription", SqlDbType.VarChar).Value = Message;


        try
        {
            conn.Open();

            cmd.ExecuteNonQuery();
        }
        finally
        {
            conn.Close();
        }
    }
    bool IErrorHandler.HandleError(Exception error)
    {

        Log("Service - " + ServiceType.FullName + Environment.NewLine + error.GetBaseException().ToString());


        //HttpContext.Current.Session.Add("LatestError", error.GetBaseException().ToString());
        //System.Net.Mail.MailMessage Mesage = new System.Net.Mail.MailMessage("sscc@lindesay.co.uk", "forbes@lindesay.co.uk", "SSCC - Error", error.GetBaseException().ToString());

        //Mesage.ReplyTo = new System.Net.Mail.MailAddress("forbes@lindesay.co.uk");

        //System.Net.Mail.SmtpClient SMTPCLIENT = new System.Net.Mail.SmtpClient("localhost");

        //SMTPCLIENT.Send(Mesage);
        return true;
    }

    void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        //FaultException<string> Fault = new FaultException<string>(error.GetBaseException().ToString());

        //fault = Message.CreateMessage(version, Fault.CreateMessageFault(), "http://microsoft.wcf.documentation/ISampleService/SampleMethodGreetingFaultFault");
    }

    #endregion
}